﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Business.Inv;
using ESOL.Common;
using ESOL.Business.Pur;
using ESOL.Business.Prod;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Hr;
using ESOL.Business.Chk;

namespace ESOL.WinUI.Inv
{
    public partial class frmMaintainImportOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public InvImportOrderEntity SelectedImportOrder { get; set; }
        private List<InvImportItemEntity> DeleteList = new List<InvImportItemEntity>();
        private List<InvImportItemEntity> mListImportItem;
        #endregion

        #region Constructor
        public frmMaintainImportOrder()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "IMO", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbOrderType, "IMT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "UNIT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit2, "UNIT", true);
        }
        private void BindDataGridDetail()
        {
            DeleteList = new List<InvImportItemEntity>();
            if (SelectedImportOrder == null)
            {
                gvDetail.DataSource = null;
                return;
            }
            DataSet ds = InvImportItemBs.GetDataSetByImportID(SelectedImportOrder.ImportOrderId, SelectedImportOrder.OrderType);

            if (ds == null || ds.Tables.Count == 0)
            {
                gvDetail.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvDetail.DataSource = dt;

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                
                if (!string.IsNullOrEmpty(dt.Rows[i]["LOCATION_ID_P"].ToString()))//LOCATION_ID_P改为LOCATION_ID
                {
                    DataTable dt_location = MstLocationBs.GetWarehouseLocationByLocationId(dt.Rows[i]["LOCATION_ID_P"].ToString());//LOCATION_ID_P改为LOCATION_ID
                    if (dt_location != null && dt_location.Rows.Count > 0)
                    {
                        dt.Rows[i]["WAREHOUSE_CODE"] = dt_location.Rows[0]["WAREHOUSE_CODE"].ToString();
                        dt.Rows[i]["WAREHOUSE_NAME"] = dt_location.Rows[0]["WAREHOUSE_NAME"].ToString();
                        dt.Rows[i]["LOCATION_CODE"] = dt_location.Rows[0]["LOCATION_CODE"].ToString();
                    }
                }
            }
            if (SelectedImportOrder.OrderType == "IMT03")//盘盈入库
            {
                foreach (DataRow dr in dt.Rows)
                {
                    dr["WAREHOUSE_CODE"] = SelectedImportOrder.WarehouseCode;
                    MstWarehouseEntity wareHouse = MstWarehouseBs.GetMstWarehouseByID(SelectedImportOrder.WarehouseCode);
                    if (dr["WAREHOUSE_CODE"] != null|| wareHouse!=null)
                    {
                        dr["WAREHOUSE_NAME"] = wareHouse.WarehouseName;
                    }
                    if (dr["LOCATION_ID"].ToString() != "")
                    {
                        dr["LOCATION_CODE"] = MstLocationBs.GetMstLocationByID(dr["LOCATION_ID"].ToString()).LocationCode;
                    }
                    else
                    {
                        dr["LOCATION_CODE"] = "自动分配";
                    }
                     
                }
            }
        }
        private void SetFields()
        {

            BindDataGridDetail();
            if (SelectedImportOrder == null)
            {
                return;
            }
            cmbOrderType.SetSelectedValue(SelectedImportOrder.OrderType);
            cmbStatus.SetSelectedValue(SelectedImportOrder.Status);

            if (ThisActionType != ActionType.New)
            {
                txtOrderCode.Text = SelectedImportOrder.OrderCode;
            }
            if (SelectedImportOrder.OrderDate != "")
            {
                dtpOrderDate.EditValue = Convert.ToDateTime(SelectedImportOrder.OrderDate);
            }

            if (!SelectedImportOrder.RelatedOrder.Equals(""))
            {
                #region 采购入库
                if (SelectedImportOrder.OrderType == "IMT01")//采购入库
                {
                    PurPurchaseArrivedEntity pa = PurPurchaseArrivedBs.GetPurchaseArrivedByID(SelectedImportOrder.RelatedOrder);
                    ChkQualityCheckingEntity cc = ChkQualityCheckingBs.GetQcOrderByID(SelectedImportOrder.RelatedOrder);

                    QcIqcOrderEntity qq = QcIqcOrderBs.GetIqcOrderByID(SelectedImportOrder.RelatedOrder);//质检未完成
                    if (qq == null)
                    {
                        MessageBox.Show("找不到相关单据！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    txtRelatedOrder.Text = qq.OrderCode;
                    txtRelatedOrder.Tag = qq;

                }
                #endregion
                #region 半成品入库
                if (SelectedImportOrder.OrderType == "IMT02")//半成品入库
                {

                    ProdPlanOrderEntity po = ProdPlanOrderBs.GetProdPlanOrderByID(SelectedImportOrder.RelatedOrder);
                    if (po == null)
                    {
                        ProdPlanOrderItemEntity poi = ProdPlanOrderItemBs.GetProdPlanOrderItemByID(SelectedImportOrder.RelatedOrder);
                        if (poi == null)
                        {
                            ChkQualityCheckingEntity cc = ChkQualityCheckingBs.GetQcOrderByID(SelectedImportOrder.RelatedOrder);
                            if (cc == null)
                            {
                                MessageBox.Show("找不到相关单据！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            txtRelatedOrder.Text = cc.CheckingCode;
                            txtRelatedOrder.Tag = cc;
                        }
                        else
                        {
                            txtRelatedOrder.Text = poi.OrderItemCode;
                            txtRelatedOrder.Tag = poi;
                        }
                    }
                    else
                    {
                        txtRelatedOrder.Text = po.PlanOrderCode;
                        txtRelatedOrder.Tag = po;
                    }

                }
                #endregion
                #region 成品入库
                if (SelectedImportOrder.OrderType == "IMT05")//成品入库
                {
                    ProdPlanOrderEntity po = ProdPlanOrderBs.GetProdPlanOrderByID(SelectedImportOrder.RelatedOrder);
                    if (po == null)
                    {
                        ProdPlanOrderItemEntity poi = ProdPlanOrderItemBs.GetProdPlanOrderItemByID(SelectedImportOrder.RelatedOrder);
                        if (poi == null)
                        {
                            ChkQualityCheckingEntity cc = ChkQualityCheckingBs.GetQcOrderByID(SelectedImportOrder.RelatedOrder);
                            if (cc == null)
                            {
                                MessageBox.Show("找不到相关单据！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            txtRelatedOrder.Text = cc.CheckingCode;
                            txtRelatedOrder.Tag = cc;
                        }
                        else
                        {
                            txtRelatedOrder.Text = poi.OrderItemCode;
                            txtRelatedOrder.Tag = poi;
                        }
                    }
                    else
                    {
                        txtRelatedOrder.Text = po.PlanOrderCode;
                        txtRelatedOrder.Tag = po;
                    }
                    //ProdPlanOrderItemEntity po = ProdPlanOrderItemBs.GetProdPlanOrderItemByID(SelectedImportOrder.RelatedOrder);
                    //if (po == null)
                    //{
                    //    MessageBox.Show("找不到相关单据！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //    return;
                    //}
                    //txtRelatedOrder.Text = po.OrderItemCode;
                    //txtRelatedOrder.Tag = po;
                }
                #endregion
                #region 盘盈入库
                if (SelectedImportOrder.OrderType == "IMT03")//盘盈入库
                {
                    InvCheckingPlanEntity ic = InvCheckingPlanBs.GetCheckingPlanByID(SelectedImportOrder.RelatedOrder);
                    if (ic == null)
                    {
                        MessageBox.Show("找不到相关单据！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    txtRelatedOrder.Text = ic.CheckingPlanCode;
                    txtRelatedOrder.Tag = ic;
                }
                #endregion
                #region 其他入库
                if (SelectedImportOrder.OrderType == "IMT06")//其它入库
                {

                }
                #endregion
            }

            txtRemark.Text = SelectedImportOrder.Remark;

            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedImportOrder.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedPerson, SelectedImportOrder.ApprovedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifyDate, SelectedImportOrder.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifyPerson, SelectedImportOrder.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtCreatDate, SelectedImportOrder.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatPerson, SelectedImportOrder.CreatedBy);
        }
        private void SetEntity()
        {
            if (ThisActionType == ActionType.New)
            {
                SelectedImportOrder = new InvImportOrderEntity();
            }

            if (cmbOrderType.SelectedValue != null && cmbOrderType.SelectedValue.ToString().Trim() != "")
            {
                SelectedImportOrder.OrderType = cmbOrderType.SelectedValue.ToString().Trim();
            }
            SelectedImportOrder.OrderCode = txtOrderCode.Text;

            if (dtpOrderDate.EditValue!=null)
            {
                SelectedImportOrder.OrderDate = dtpOrderDate.EditValue.ToString() ;
            }
            if (txtRelatedOrder.Tag != null)
            {
                switch (cmbOrderType.SelectedValue.ToString())
                {
                    case "IMT01":
                        //SelectedImportOrder.RelatedOrder = ((PurPurchaseArrivedEntity)txtRelatedOrder.Tag).ArrivedId;
                        SelectedImportOrder.RelatedOrder = ((QcIqcOrderEntity)txtRelatedOrder.Tag).OrderId;
                        break;
                    case "IMT02":
                        //SelectedImportOrder.RelatedOrder = ((ProdPlanOrderItemEntity)txtRelatedOrder.Tag).PlanOrderItemId;
                        //SelectedImportOrder.RelatedOrder = ((ChkQualityCheckingEntity)txtRelatedOrder.Tag).CheckingId;
                        SelectedImportOrder.RelatedOrder = ((ProdPlanOrderEntity)txtRelatedOrder.Tag).PlanOrderId;
                        break;
                    case "IMT05":
                        //SelectedImportOrder.RelatedOrder = ((ProdPlanOrderItemEntity)txtRelatedOrder.Tag).PlanOrderItemId;
                        SelectedImportOrder.RelatedOrder = ((ProdPlanOrderEntity)txtRelatedOrder.Tag).PlanOrderId;
                        break;
                }

            }
            SelectedImportOrder.OrderPerson = CommonParameter.CurrentUser.PersonId;

            if (cmbStatus.SelectedValue != null && cmbStatus.SelectedValue.ToString().Trim() != "")
            {
                SelectedImportOrder.Status = cmbStatus.SelectedValue.ToString();
            }

            SelectedImportOrder.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedImportOrder.ImportOrderId = Guid.NewGuid().ToString();
                SelectedImportOrder.Status = "IMO01";
                SelectedImportOrder.CreatedDate = DateTime.Now;
                SelectedImportOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedImportOrder.LastModifiedDate = DateTime.Now;
                SelectedImportOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtOrderCode.Text))
            {
                MessageBox.Show("入库单编号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            if (string.IsNullOrEmpty(cmbOrderType.Text))
            {
                MessageBox.Show("入库类型不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            if (dtpOrderDate.EditValue == null)
            {
                MessageBox.Show("入库单时间不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvDetail.DataSource == null || gridView1.RowCount == 0)
            {
                MessageBox.Show("入库单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = (DataTable)gvDetail.DataSource;
            foreach (DataRow dr in dt.Rows)
            {
                //if (string.IsNullOrEmpty(gvDetail.Rows[i].Cells["cWareHouseCode"].Value.ToString()))
                //{
                //    MessageBox.Show("列表第" + i.ToString() + "行，仓库编码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    return false;
                //}
                if (ThisActionType == ActionType.Approve)
                {
                    //    DataTable dt = (DataTable)gvDetail.DataSource;
                    //    if (string.IsNullOrEmpty(dt.Rows[i]["WAREHOUSE_CODE"].ToString()))
                    //    {
                    //        MessageBox.Show("列表第" + i.ToString() + "行，仓库编码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //        return false;
                    //    }

                    decimal Qty = CommonFunctions.ToDecimal(dr["QTY"]);
                    string Code = CommonFunctions.ToString((dr["WAREHOUSE_CODE"]));
                    if (Qty == 0)
                    {
                        MessageBox.Show("入库数量不能为0！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    if (Code == null)
                    {
                        MessageBox.Show("仓库编码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = InvImportOrderBs.SaveImportOrder(true, SelectedImportOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = InvImportOrderBs.SaveImportOrder(false, SelectedImportOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    
                    SelectedImportOrder.ApprovedDate = DateTime.Now;
                    SelectedImportOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = InvImportOrderBs.SaveApproveImport(SelectedImportOrder, dt);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        #endregion

        #region Events
        private void frmMaintainImportOrder_Load(object sender, EventArgs e)
        {
            BindComboBox();
            SetFields();
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_SaveNew()
        {

        }
        protected override void Click_Approve()
        {
            if (SelectedImportOrder == null)
            {
                return;
            }
            SelectedImportOrder.Status = "IMO03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (SelectedImportOrder == null)
            {
                return;
            }
            SelectedImportOrder.Status = "IMO04";
            bool successful=InvImportOrderBs.UpdateInvImportOrder(SelectedImportOrder);
            if (successful == true)
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtRelatedOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            
        }

        private void repProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        private void repWareHouseCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (!SelectedImportOrder.OrderType.Equals("IMT03"))
            {
                if (!string.IsNullOrEmpty(drSelectedDetail["LOCATION_ID_P"].ToString()))
                {
                    MessageBox.Show("生产单已经指定库位，不可修改库位！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            frmMaintainWareHouseQuery frm = new frmMaintainWareHouseQuery();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                drSelectedDetail["WAREHOUSE_CODE"] = frm.SelectedWarehouse.WarehouseCode;
                drSelectedDetail["WAREHOUSE_NAME"] = frm.SelectedWarehouse.WarehouseName;
                drSelectedDetail["LOCATION_CODE"] = "自动分配";

            }
        }

        private DataRow drSelectedDetail;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelectedDetail = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void ItemNew_Click(object sender, EventArgs e)
        {
            if (gvDetail.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvDetail.DataSource;
            DataRow dr = dt.NewRow();
            //SetDataRowByApplicationItem(dr, entity);
            dt.Rows.Add(dr);
        }

        private void ItemDelete_Click(object sender, EventArgs e)
        {
            if (gvDetail.DataSource == null)
            {
                return;
            }
            if (drSelectedDetail == null)
            {
                return;
            }
            if (drSelectedDetail.RowState != DataRowState.Added)
            {
                InvImportItemEntity entity = new InvImportItemEntity(drSelectedDetail);
                DeleteList.Add(entity);
            }
            DataTable dt = gvDetail.DataSource as DataTable;
            dt.Rows.Remove(drSelectedDetail);

        }

        #endregion

        private void repLocation_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (!SelectedImportOrder.OrderType.Equals("IMT03"))
            {
                if (!string.IsNullOrEmpty(drSelectedDetail["LOCATION_ID_P"].ToString()))
                {
                    MessageBox.Show("生产单已经指定库位，不可修改库位！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            frmMaintainLocationQuery frm = new frmMaintainLocationQuery();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                drSelectedDetail["LOCATION_CODE"] = frm.SelectLocation.LocationCode;
                drSelectedDetail["LOCATION_ID_P"] = frm.SelectLocation.LocationId;
            }
        }





    }
}